package www.dianbaozu.com.ui.find.searchServer

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import androidx.core.widget.addTextChangedListener
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.dylanc.loadinghelper.LoadingHelper
import com.dylanc.loadinghelper.ViewType
import dagger.hilt.android.AndroidEntryPoint
import www.dianbaozu.com.R
import www.dianbaozu.com.databinding.FragmentSearchServerBinding
import www.dianbaozu.com.extension.requestServerDetails
import www.dianbaozu.com.ui.find.recommendationServer.adapter.RecommendationServerAdapter
import www.dianbaozu.com.ui.server.JoiningServerFragment
import www.wen.com.common.lib.base.fragment.BaseListFragment
import www.wen.com.common.lib.base.module.BaseViewModel
import www.wen.com.common.lib.data.entities.NavigationFromType
import www.wen.com.common.lib.data.entities.ServerEntity
import www.wen.com.common.lib.data.entities.ViewPagePosition
import www.wen.com.common.lib.extension.*
import www.wen.com.common.lib.helper.loading.KeyHelper
import www.wen.com.common.lib.helper.loading.LoadingAdapter
import www.wen.com.common.lib.helper.loading.TitleBarUniversalAdapter
import www.wen.com.common.lib.view.SpaceItemDecoration


/**
 * @author WEN
 * @Description:主页发现 - 推荐服务器列表
 * @date 2020//25 17:48
 */
@AndroidEntryPoint
class SearchServerFragment :
    BaseListFragment<FragmentSearchServerBinding, ServerEntity, ServerEntity>() {

    private var serverIdOrName = ""

    private lateinit var mAdapter: RecommendationServerAdapter

    override val mRecyclerView: RecyclerView
        get() = dataBinding.rvServerList

    override fun provideAdapter(): BaseQuickAdapter<ServerEntity, BaseViewHolder> =
        RecommendationServerAdapter().apply {
            mAdapter = this
        }

    override fun provideLayoutManager(): RecyclerView.LayoutManager =
        GridLayoutManager(context, 2)

    override val isAddItemDecoration: Boolean
        get() = true

    override fun provideItemDecoration(): RecyclerView.ItemDecoration =
        SpaceItemDecoration(12, 2)

    override val mIsEnableEmpty: Boolean
        get() = false

    override val mIsEnableLoading: Boolean
        get() = false

    private val searchServerViewModel: SearchServerViewModel by viewModels()

    override fun configurationLoadingHelper(loadingHelper: LoadingHelper): LoadingHelper {
        loadingHelper.register(ViewType.LOADING, LoadingAdapter(R.color.color1B1D22))
        loadingHelper.register(ViewType.TITLE, getTitleBarUniversalAdapter())
        loadingHelper.setDecorHeader(ViewType.TITLE)
        return loadingHelper
    }

    override val viewModel: BaseViewModel
        get() = searchServerViewModel

    override fun isEnableLoadingHelper(): Boolean = true

    override fun getTitleBarUniversalAdapter(): TitleBarUniversalAdapter =
        TitleBarUniversalAdapter(requireActivity(), "查找服务器", action = ::titleAction)

    override fun getLayoutId(): Int = R.layout.fragment_search_server

    override fun lazyInitView() {
        super.lazyInitView()
        observeListen()
        serverIdOrName = arguments?.getString(KeyHelper.BUNDLE_DATA)?:""

        dataBinding.apply {
            etSearch.addTextChangedListener {
                serverIdOrName = it.toString().trim()
                launchRequest(true)
            }
            etSearch.banEnterKey()
        }


        dataBinding.etSearch.setText(serverIdOrName)

    }

    private fun observeListen() {
        searchServerViewModel.uiState.observe(this) {
            if (it.showSuccess != null) {
                if(it.isRefresh){
                    if (it.showSuccess!!.isEmpty()) {
                        mAdapter.setList(null)
                        mAdapter.setEmptyView(
                                LayoutInflater.from(requireActivity())
                                        .inflate(R.layout.layout_empty, null, false)
                        )
                    } else {
                        mAdapter.setList(it.showSuccess)
                    }
                }else{
                    mAdapter.addData(it.showSuccess!!)
                }
            }
        }
    }

    private fun launchRequest(isRefresh: Boolean) {
        if (serverIdOrName.isEmpty()) {
            return
        }
        searchServerViewModel.requestGeneralListData(
            requiredParameter = serverIdOrName,
            isRefresh = isRefresh
        )
    }

    override fun onItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
        val data = adapter.data[position] as ServerEntity
        if (data.serverMember != null) {
            searchServerViewModel.requestServerDetails(
                    viewModelScope = lifecycleScope,
                    data.serverId,
            ) {
                it.fromType = if(isExitFragment(JoiningServerFragment::class.java)) NavigationFromType.FROM_SERVER else NavigationFromType.FROM_RECOMMENDATION
                nav(R.id.action_searchServerFragment_to_serverDetailsFragment, Bundle().apply {
                    putParcelable(KeyHelper.BUNDLE_DATA, it)
                })
            }
        } else {
            searchServerViewModel.requestServerPreview(data.serverId) {
                postObject(KeyHelper.INSERT_PREVIEW_SERVER_KEY, it)
                postObject(KeyHelper.MAIN_VIEWPAGER_POSITION_KEY, ViewPagePosition(0))
                findNavController().popBackStack(R.id.mainFragment,false)
            }
        }

    }

    override fun onLoadMore() {
        launchRequest(false)
    }

    override fun onReload() {
        launchRequest(false)
    }

    override fun onClick(v: View) {
        navBack()
    }

}



